package com.ship.dispatch.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.Page;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.SmShipCrew;
import com.ship.dispatch.bean.SmShipCrewDetail;
import com.ship.dispatch.bean.SmShipCrewDetailChange;
import com.ship.dispatch.bean.SmShipCrewRecord;
import com.ship.dispatch.bean.bpm.BpmJsonModelDO;
import com.ship.dispatch.bean.shipBusiness.SmShipReport;
import com.ship.dispatch.bo.SmShipCrewImportBo;
import com.ship.dispatch.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 船员管理 前端控制器
 *
 * @author zhangyh
 * @since 2024-01-10
 */
@RestController
@RequestMapping("/ship/crew")
@Api(value = "smShipCrew", tags = "船员管理前端控制器")
public class SmShipCrewController {

    @Autowired
    private SmShipCrewService smShipCrewService;

    @Autowired
    private SmShipCrewDetailChangeService smShipCrewDetailChangeService;

    @Autowired
    private SmShipCrewRecordService smShipCrewRecordService;

    @Autowired
    private SmShipCrewDetailService smShipCrewDetailService;

    @Autowired
    private ExportService exportService;

    /**
     * 船舶基础信息分页
     *
     * @param smShipCrew
     * @return
     */
    @ApiOperation(value = "船舶基础信息分页")
    @PostMapping("/base/page")
    public JsonResult<Page<SmShipCrew>> basePage(@RequestBody SmShipCrew smShipCrew) {
        Page<SmShipCrew> page = smShipCrewService.page(smShipCrew,new QueryWrapper<SmShipCrew>().ne("del_apply",2));
        return JsonResult.success(page);
    }

    /**
     * 船舶基础信息分页导出
     *
     * @return
     */
    @ApiOperation(value = "船舶基础信息分页导出")
    @PostMapping("/base/page/export")
    @Log(title = "船舶基础信息分页导出",businessType = BusinessType.EXPORT)
    public JsonResult basePageExport(@RequestBody SmShipCrew smShipCrew) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(CollectionUtil.isNotEmpty(smShipCrew.getIds())){
            queryWrapper.in("id",smShipCrew.getIds());
        }
        List<SmShipCrew> exportList = smShipCrewService.pageExportList(smShipCrew, queryWrapper,new LinkedList<>());
        if (CollectionUtil.isNotEmpty(exportList)){
            exportList.forEach(item -> {

            });
        }
        Field[] fields = SmShipCrew.class.getDeclaredFields();
        String url = exportService.pageExport(exportList,fields,exportService.listStrByModuleAndUser
                ("sm_ship_crew", SecurityUtils.getUserId()), "船员信息");
        return JsonResult.success(url);
    }

    /**
     * 船员批量excel导入
     *
     * @return
     */
    @ApiOperation(value = "船员批量excel导入")
    @PostMapping(value = "/base/import")
    @Log(title = "船员批量excel导入",businessType = BusinessType.IMPORT)
    public JsonResult baseImport(@RequestBody SmShipCrewImportBo bo) {
        return smShipCrewService.baseImport(bo);
    }

    /**
     * 船舶基础信息编辑
     *
     * @param smShipCrew
     * @return
     */
    @ApiOperation(value = "船舶基础信息编辑")
    @PostMapping("/base/update")
    @Log(title = "船舶基础信息编辑",businessType = BusinessType.UPDATE)
    public JsonResult baseUpdate(@RequestBody SmShipCrew smShipCrew) {
        smShipCrewService.baseUpdate(smShipCrew);
        return JsonResult.success();
    }

    /**
     * 船舶基础信息详情
     *
     * @param shipCrewId
     * @return
     */
    @ApiOperation(value = "船舶基础信息详情")
    @GetMapping("/base/detail/{shipCrewId}")
    public JsonResult<SmShipCrew> baseDetail(@PathVariable(value = "shipCrewId") Long shipCrewId) {
        return JsonResult.success(smShipCrewService.baseDetail(shipCrewId));
    }

    /**
     * 校验船只是否存在
     *
     * @param smShipCrew
     * @return
     */
    @ApiOperation(value = "校验船只是否存在")
    @PostMapping("/base/check")
    public JsonResult baseCheck(@RequestBody SmShipCrew smShipCrew) {
        if(StringUtils.isBlank(smShipCrew.getShipName())){
            return JsonResult.failed("船舶名称不能为空");
        }
        Long count = smShipCrewService.getBaseMapper().selectCount(
                new LambdaQueryWrapper<SmShipCrew>()
                .eq(SmShipCrew::getShipName,smShipCrew.getShipName())
        );
        if(count > 0){
            return JsonResult.failed("该船只船员信息已存在，请找到对应船只后，点击查看进入详情页编辑");
        }
        return JsonResult.success(count);
    }

    /**
     * 船舶基础信息删除
     *
     * @param shipCrewId
     * @return
     */
    @ApiOperation(value = "船舶基础信息删除")
    @DeleteMapping("/base/delete/{shipCrewId}")
    @Log(title = "删除船员基础信息",businessType = BusinessType.DELETE)
    public JsonResult<SmShipCrew> baseDelete(@PathVariable(value = "shipCrewId") Long shipCrewId) {
        smShipCrewService.baseDelete(shipCrewId);
        return JsonResult.success();
    }


    /**
     * 船员信息新增
     *
     * @param smShipCrewDetail
     * @return
     */
    @ApiOperation(value = "船员信息新增")
    @PostMapping("/detail/add")
    @Log(title = "新增船员信息",businessType = BusinessType.INSERT)
    public JsonResult detailAdd(@RequestBody SmShipCrewDetail smShipCrewDetail) {
        return smShipCrewDetailService.detailAdd(smShipCrewDetail);
    }

    /**
     * 获取当前用户当前船只下的船员缓存信息
     *
     * @param shipCrewId
     * @return
     */
    @ApiOperation(value = "获取当前用户当前船只下的船员缓存信息")
    @GetMapping("/detail/temp/{shipCrewId}")
    public JsonResult<SmShipCrewDetail> detailTempCrew(@PathVariable(value = "shipCrewId") Long shipCrewId) {
        return JsonResult.success(smShipCrewService.detailTempCrew(shipCrewId));
    }

    /**
     * 船员信息编辑
     *
     * @param smShipCrewDetail
     * @return
     */
    @ApiOperation(value = "船员信息编辑")
    @PostMapping("/detail/update")
    @Log(title = "船员信息编辑",businessType = BusinessType.UPDATE)
    public JsonResult detailUpdate(@RequestBody SmShipCrewDetail smShipCrewDetail) {
        return smShipCrewService.detailUpdate(smShipCrewDetail);
    }

    /**
     * 船员信息分页
     *
     * @param smShipCrewDetail
     * @return
     */
    @ApiOperation(value = "船员信息分页")
    @PostMapping("/detail/page")
    public JsonResult<Page<SmShipCrewDetail>> detailPage(@RequestBody SmShipCrewDetail smShipCrewDetail) {
        smShipCrewDetail.setIsTemp("0");
        Page<SmShipCrewDetail> page = smShipCrewDetailService.page(smShipCrewDetail,new QueryWrapper<>());
        return JsonResult.success(page);
    }

    /**
     * 船员信息列表
     *
     * @param smShipCrewDetail
     * @return
     */
    @ApiOperation(value = "船员信息列表")
    @PostMapping("/detail/listForSearch")
    public JsonResult<List<SmShipCrewDetail>> detailList(@RequestBody SmShipCrewDetail smShipCrewDetail) {
        smShipCrewDetail.setIsTemp("0");
        List<SmShipCrewDetail> resultList = smShipCrewDetailService.pageExportList(smShipCrewDetail, new QueryWrapper<>(),new LinkedList<>());
        return JsonResult.success(resultList);
    }

    /**
     * 船员信息分页导出
     *
     * @return
     */
    @ApiOperation(value = "船员信息分页导出")
    @PostMapping("/detail/page/export")
    @Log(title = "船员信息分页导出",businessType = BusinessType.EXPORT)
    public JsonResult detailPageExport(@RequestBody SmShipCrewDetail smShipCrewDetail) {
        smShipCrewDetail.setIsTemp("0");
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(smShipCrewDetail.getIds() != null && smShipCrewDetail.getIds().size() > 0){
            queryWrapper.in("id",smShipCrewDetail.getIds());
        }
        List<SmShipCrewDetail> exportList = smShipCrewDetailService.pageExportList(smShipCrewDetail, queryWrapper,new LinkedList<>());
        for (SmShipCrewDetail shipCrewDetail : exportList) {
            shipCrewDetail.setIsHigh(StringUtils.equals("1",shipCrewDetail.getIsHigh()) ? "是" : "否");
            shipCrewDetail.setStatus(StringUtils.equals("1",shipCrewDetail.getStatus()) ? "在船" : "离船");
            if (null != shipCrewDetail.getExpiraDate()){
                Date date = new Date();
                LocalDate startDate = LocalDate.of(date.getYear() + 1900, date.getMonth() + 1, date.getDate());
                LocalDate endDate = LocalDate.of(shipCrewDetail.getExpiraDate().getYear() + 1900, shipCrewDetail.getExpiraDate().getMonth() + 1, shipCrewDetail.getExpiraDate().getDate());
                long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
                if (daysBetween >= 0){
                    shipCrewDetail.setWarningMessage("船员证到期还有"+daysBetween+"天");
                }else {
                    shipCrewDetail.setWarningMessage("船员证已超期"+daysBetween+"天");
                }
            }
        }
        Field[] fields = SmShipCrewDetail.class.getDeclaredFields();
        String url = exportService.pageExport(exportList,fields,exportService.listStrByModuleAndUser
                ("sm_ship_crew_detail",SecurityUtils.getUserId()), "船员信息");
        return JsonResult.success(url);
    }



    /**
     * 船员异动信息分页
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "船员异动信息分页")
    @PostMapping("/detail/change/page")
    public JsonResult<Page<SmShipCrewDetailChange>> detailChangePage(@RequestBody SmShipCrewDetailChange dto) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("updated_time");
        Page<SmShipCrewDetailChange> page = smShipCrewDetailChangeService.page(dto,queryWrapper);
        for (SmShipCrewDetailChange detailChange : page.getList()) {
            detailChange.setStatus(StringUtils.equals("1",detailChange.getStatus()) ? "上船":"离船");
        }
        return JsonResult.success(page);
    }

    /**
     * 船员异动信息分页导出
     *
     * @return
     */
    @ApiOperation(value = "船员异动信息分页导出")
    @PostMapping("/detail/change/page/export")
    @Log(title = "船员异动信息分页导出",businessType = BusinessType.EXPORT)
    public JsonResult detailPageExport(@RequestBody SmShipCrewDetailChange dto) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("updated_time");
        if(dto.getIds() != null && dto.getIds().size() > 0){
            queryWrapper.in("id",dto.getIds());
        }
        List<SmShipCrewDetailChange> exportList = smShipCrewDetailChangeService.pageExportList(dto, queryWrapper,new LinkedList<>());
        for (SmShipCrewDetailChange detailChange : exportList) {
            detailChange.setStatus(StringUtils.equals("1",detailChange.getStatus()) ? "上船":"离船");
        }
        Field[] fields = SmShipCrewDetailChange.class.getDeclaredFields();
        List<String> propertyNames = new ArrayList<>();
        for (Field field : fields) {
            if(StringUtils.equals("shipCrewId",field.getName())){
                continue;
            }
            propertyNames.add(field.getName());
        }
        String url = exportService.pageExport(exportList,fields,propertyNames, "船员异动信息");
        return JsonResult.success(url);
    }

    /**
     * 船员管理操作记录
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "船员管理操作记录")
    @PostMapping("/detail/record/list")
    public JsonResult<List<SmShipCrewRecord>> detailRecordList(@RequestBody SmShipCrewRecord dto) {
        List<SmShipCrewRecord> list = smShipCrewRecordService.getBaseMapper().selectList(
                new LambdaQueryWrapper<SmShipCrewRecord>()
                .eq(dto.getShipCrewId() != null,SmShipCrewRecord::getShipCrewId,dto.getShipCrewId())
                .orderByDesc(SmShipCrewRecord::getOperateTime)
        );
        return JsonResult.success(list);
    }
}
